#!/usr/bin/env python
# -*- coding:utf-8 -*-

"""
   定义应用初始化
"""

from flask import Flask
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from .setting import Settings

# 数据库
db = SQLAlchemy()
limiter = None

# 工厂模式创建app应用对象
def create_app(config_name):
    """
    创建flask的应用对象
    :param config_name: string 配置模式的名字  （"develop", "product"）
    :return:
    """
    app = Flask(__name__)
    #限制访问次数
    global limiter
    limiter = Limiter(
        app,
        key_func=get_remote_address,  # 根据访问者的IP记录访问次数
        default_limits=["200 per day", "50 per hour"]  # 默认限制，一天最多访问200次，一小时最多访问50次
    )

    # 根据配置模式的名字获取配置参数的类
    app.config.from_object(Settings)
    # 使用app初始化db
    db.init_app(app)

    # 利用Flask_session将数据保存的session中
    # Session(app)

    '''
      整个应用的蓝图加载和注册
    '''
    # apiversion blueprint register
    from api_1_0.apiVersionResource import apiversion_blueprint
    app.register_blueprint(apiversion_blueprint, url_prefix="/api_1_0")

    # careInfo blueprint register
    from api_1_0.careInfoResource import careinfo_blueprint
    app.register_blueprint(careinfo_blueprint, url_prefix="/api_1_0")
    
    # collectionInfo blueprint register
    from api_1_0.collectionInfoResource import collectioninfo_blueprint
    app.register_blueprint(collectioninfo_blueprint, url_prefix="/api_1_0")
    
    # commentInfo blueprint register
    from api_1_0.commentInfoResource import commentinfo_blueprint
    app.register_blueprint(commentinfo_blueprint, url_prefix="/api_1_0")
    
    # historyInfo blueprint register
    from api_1_0.historyInfoResource import historyinfo_blueprint
    app.register_blueprint(historyinfo_blueprint, url_prefix="/api_1_0")
    
    # passageInfo blueprint register
    from api_1_0.passageInfoResource import passageinfo_blueprint
    app.register_blueprint(passageinfo_blueprint, url_prefix="/api_1_0")
    
    # recommandInfo blueprint register
    from api_1_0.recommandInfoResource import recommandinfo_blueprint
    app.register_blueprint(recommandinfo_blueprint, url_prefix="/api_1_0")
    
    # upvoteInfo blueprint register
    from api_1_0.upvoteInfoResource import upvoteinfo_blueprint
    app.register_blueprint(upvoteinfo_blueprint, url_prefix="/api_1_0")
    
    # userInfo blueprint register
    from api_1_0.userInfoResource import userinfo_blueprint
    app.register_blueprint(userinfo_blueprint, url_prefix="/api_1_0")

    # accuseInfo blueprint register
    from api_1_0.accuseInfoResource import accuseinfo_blueprint
    app.register_blueprint(accuseinfo_blueprint, url_prefix="/api_1_0")

    # adminInfo blueprint register
    from api_1_0.adminInfoResource import admininfo_blueprint
    app.register_blueprint(admininfo_blueprint, url_prefix="/api_1_0")
    return app
